package com.demo.camunda.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.demo.camunda.entity.MsgclientT;
import com.demo.camunda.service.impl.uploadTExcelImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
public class ListenerExcelT<T> implements ReadListener<T> {

    private final uploadTExcelImpl uploadTExcel;


    /**
     * 每隔4500条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 4500;
    /**
     * 缓存的数据
     */
    private List<T> cachedDataList = new ArrayList<>(0);

    private final AtomicInteger count = new AtomicInteger(0);

    public ListenerExcelT(uploadTExcelImpl uploadTExcel) {
        this.uploadTExcel = uploadTExcel;
    }


    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        ReadListener.super.onException(exception, context);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        ReadListener.super.invokeHead(headMap, context);
    }

    @Override
    public void invoke(T entity, AnalysisContext context) {
        count.addAndGet(1);

        //   log.info("解析到一条数据:{}", JSON.toJSONString(entity));

        cachedDataList.add(entity);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {

            uploadTExcel.insertList2((List<MsgclientT>) cachedDataList);
            //  batchInsert();
            // 存储完成清理 list
            //cachedDataList.clear();
            cachedDataList = new ArrayList<>(0);
        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        ReadListener.super.extra(extra, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (count.get() > 0 && CollectionUtils.isNotEmpty(cachedDataList)) {
            uploadTExcel.insertList2((List<MsgclientT>) cachedDataList);
            log.info("第二个sheet一共获取了:{}条数据", count.get());
            //batchInsert();
        }
        log.info("第二个sheet所有数据解析完成！");
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return true;
    }
}
